package com.example.demo.utils;


import com.example.demo.dto.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 缓存进redis中变为了LinkedHashMap
 *
 * 进行数据转换
 */
@Component
public class GrantedAuthorityFormatter {
    @Autowired
    private RedisUtil redisUtil;

    public LoginUser getLoginUser(String tokenUsername){
        //缓存进redis中变为了LinkedHashMap
        Map<String,Object> map = redisUtil.getCacheObject(tokenUsername);
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        List<Map<String,String>> list = (List<Map<String, String>>) map.get("grantedAuthorities");

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        list.forEach((t)->{
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(t.get("authority"));
            grantedAuthorities.add(simpleGrantedAuthority);
        });

        return new LoginUser(username,password,grantedAuthorities);
    }
}
